package com.imooc.distributedemo;

import cn.hutool.core.util.StrUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class SHA256Demo {

    private static final String ALLOWED_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
    private static final int MAX_LENGTH = 64;

    public static String generateRandomString() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder("AK-");

        // 填充剩余的随机串
        for (int i = 0; i < MAX_LENGTH - 3; i++) {
            int randomIndex = random.nextInt(ALLOWED_CHARACTERS.length());
            sb.append(ALLOWED_CHARACTERS.charAt(randomIndex));
        }

        return sb.toString();
    }

    public static String sha256(String base) {
        try {
            // 创建一个MessageDigest实例
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            // 使用指定的字节更新摘要
            digest.update(base.getBytes());
            // 计算摘要
            byte[] hashBytes = digest.digest();
            // 将摘要转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String originalString = "Hello, World!";
//        企业别名
//        5664510592625513
//        主账号 ID
//        5664510592625513
//        登录名称
//        TextScan@5664510592625513.onaliyun.com复制
//        UID
//        213706824049964168
        String appId = "app1";
        String appKey = "LTAI5tCnS5rVH3Knn2VMah7x";
        String secretKey = "kgyP9w4FIBofdWJPfTJz9YIyyAJ9tJ";
        String userid = "213706824049964168"; // 213706824049964168
        String nonce = generateRandomString();
        String role = "acs:ram::5664510592625513:user/TextScan";

        appId = "ab0a8d7cb5c2";
        appKey = "d32884b0fb573766eb176f3397681910";
//        userid = "5664510592625513";
//        role = "213706824049964168";
        long timestamp = System.currentTimeMillis()+60*60*24*15;
        String str = StrUtil.concat(true,appId,appKey,userid,
                nonce,String.valueOf(timestamp),role);
        String realHashString = sha256(str);
        String hashedString = sha256(originalString);
        System.out.println("Original: " + originalString);
        System.out.println("SHA-256 Hashed: " + hashedString);
    }
}
